import { Space, Table, Drawer } from 'antd';
import { useEffect, useState } from 'react';
import { Button, message, Popconfirm } from 'antd';
import { Checkbox, Form, Input } from 'antd';
import pp from '../../../api/index'
import axios from 'axios';
function Index() {
  const [list, setList] = useState([])
  const [pageSize, setPageSize] = useState(10)
  const [page, setPage] = useState(1)
  const [total, setTotal] = useState()
  // =====================================================列表
  const getList = () => {
    axios.get('/api/article/list').then(res => {
      console.log(res.data.rows);
      setList(res.data.rows)
      setTotal(res.data.count)
    })
  }
  useEffect(() => {
    getList()
  }, [])
  // ==========================================================分页
  const changePage = (page: string, pageSize: string) => {
    setPage(page)
    setPageSize(pageSize)

  }
  const columns = [
    {
      title: 'id',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '题目',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '内容',
      dataIndex: 'content',
      key: 'content',
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
    },
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Popconfirm
            title="提示"
            description="您确定要删除吗?"
            onConfirm={() => confirm(record)}
            onCancel={cancel}
            okText="确定"
            cancelText="取消"
          >
            <Button danger>删除</Button>
          </Popconfirm>
          <Button onClick={() => bj(record)}>编辑</Button>
        </Space>
      ),
    },
  ];
  // ==================================================删除
  const confirm = (record) => {
    setList(prev => prev.filter(item => item.id !== record.id))
  };
  const cancel = e => {
    console.log(e);
    message.error('Click on No');
  };
  // =================================================================新增和编辑
  const [open, setOpen] = useState(false);
  const [title, setTitle] = useState('')
  const [form] = Form.useForm()
  const onClose = () => {
    setOpen(false);
  };
  const xz = () => {
    setOpen(true)
    setTitle('新增')
    form.resetFields()
  }
  const [id, setId] = useState()
  const bj = (record) => {
    setOpen(true)
    setTitle('编辑')
    form.setFieldsValue(record)
    setId(record.id)
  }
  const onFinish = (values) => {
    console.log('Success:', values);
    const data = {
      "title": values.title,//文章标题
      "content": values.content,//文章内容
      "tagList": ["HTTP"],//标签  array[string]
      "categoryList": ["HTTP"],//分类  array[string]
      "authorId": 47529555//用户id 暂时写死47529555 登陆成功后返回的用户信息
    }
    if (title === '新增') {
      // 新增
      pp.post('/api/article', data).then(res => {
        console.log(res);
        getList()
        setOpen(false)
        alert('新增成功')
      })
    } else if (title === '编辑') {
      // 编辑
      pp.put(`/api/article/${id}`, { ...values, id: id }).then(res => {
        console.log('编辑', res);
        getList()
        setOpen(false)
        alert('编辑成功')
      })
    }
  };
  const onFinishFailed = errorInfo => {
    console.log('Failed:', errorInfo);


  };
  // =================================================================搜索
  const [values,setvalues] =useState('')
  const onFinish1 = values => {
    console.log('Success:', values);
    axios.get('/api/article/list',{
      params:{
        page:page,
        pageSize:pageSize,
        keyword:values.title
      }
    }).then(res => {
      console.log(res.data.rows);
      setList(res.data.rows)
    })
    
  };
  const onFinishFailed1 = errorInfo => {
    console.log('Failed:', errorInfo);
  };
  const [addfrom]=Form.useForm()
  const cz=()=>{
    addfrom.resetFields()
    getList()
  }
  return (
    <div>
      <Form
        name="basic"
        form={addfrom}
        layout='inline'
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        style={{ maxWidth: 600 }}
        initialValues={{ remember: true }}
        onFinish={onFinish1}
        onFinishFailed={onFinishFailed1}
        autoComplete="off"
      >
        <Form.Item
          label="题目"
          name="title"
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="内容"
          name="content"
        >
          <Input/>
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">
            搜索
          </Button>
        
        </Form.Item>
      </Form>
      <div>
        <Button type="primary" onClick={xz} style={{marginRight:'20px'}}>
          新增
        </Button>
        <Button type="primary" htmlType="submit" onClick={cz}>
            重置
          </Button>
        <Drawer

          title={title}
          closable={{ 'aria-label': 'Close Button' }}
          onClose={onClose}
          open={open}
        >
          <Form
            name="basic"
            form={form}
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            style={{ maxWidth: 600 }}
            initialValues={{ remember: true }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete="off"
          >
            <Form.Item
              label="id"
              name="id"
              rules={[{ required: true, message: '请输入内容!' }]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="题目"
              name="title"
              rules={[{ required: true, message: '请输入内容!' }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="内容"
              name="content"
              rules={[{ required: true, message: '请输入内容!' }]}
            >
              <Input />
            </Form.Item>

            <Form.Item label={null}>
              <Button type="primary" htmlType="submit">
                提交
              </Button>
            </Form.Item>
          </Form>
        </Drawer>
      </div>
      <Table columns={columns} dataSource={list}
        pagination={{
          total: total,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: total => `Total ${total} items`,
          changePage: changePage
        }}

      />
    </div>
  )
}

export default Index
